package cn.fl.splrate.controller;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.logger.eum.LogExceptionEnum;
import cn.cmm.base.framework.logger.eum.LogOperEnum;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.splrate.service.ISplRateRelInfoService;
import cn.fl.splrate.transform.SplRateRelInfoVOTransform;
import cn.fl.splrate.utils.ImportSplRateList;
import cn.fl.splrate.vo.SplRateRelInfoVO;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import fl.constant.facade.framework.constant.BusinessIdConstant;
import fl.mongo.facade.spl.api.ISplRelDataOpRecApiService;
import fl.mongo.facade.spl.dto.SplRelDataOpRecDTO;
import fl.spl.facade.framework.constant.SplSystemConstant;
import fl.spl.facade.framework.enums.CommonOpTypCdEnum;
import fl.spl.facade.framework.enums.SplGrpRelInfoSrcEnum;
import fl.spl.facade.framework.enums.common.MagicNumReplaceEnum;
import fl.spl.facade.framework.enums.splrate.BasicDataRelOpBizTypCdEnum;
import fl.spl.facade.framework.enums.splrate.FileOpRelStsCdEnum;
import fl.spl.facade.framework.enums.splrate.SplRateStarLvlEnum;
import fl.spl.facade.splrate.api.IParseTempFileRecQueryApiService;
import fl.spl.facade.splrate.api.ISplRateRelInfoQueryApiService;
import fl.spl.facade.splrate.condition.ParseTempFileRecQC;
import fl.spl.facade.splrate.condition.SplRateRelInfoQC;
import fl.spl.facade.splrate.constant.SplRateRelInfoConstant;
import fl.spl.facade.splrate.dto.ParseTempFileRecDTO;
import fl.spl.facade.splrate.dto.SplRateRelInfoDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Description: 经销商评级相关信息 控制层
 */
@Controller
@RequestMapping("/splrate/splraterelinfo")
public class SplRateRelInfoController extends BaseController {

    /**
     * SplRateRelInfo 服务层BEAN
     */
    @Autowired
    private ISplRateRelInfoService splRateRelInfoService;

    @Autowired
    private ISysDictionaryApiService sysDictionaryApiService;

    @Autowired
    private ISplRateRelInfoQueryApiService splRateRelInfoQueryApiService;

    @Autowired
    private IParseTempFileRecQueryApiService parseTempFileRecQueryApiService;

    @Autowired
    private ISplRelDataOpRecApiService splRelDataOpRecApiService;

    private ExecutorService executorService = new ThreadPoolExecutor(MagicNumReplaceEnum.REP_NON_YESNO_VAL.getVal(), MagicNumReplaceEnum.REP_DEFAULT_LEN_FOUR.getVal(), 10, TimeUnit.SECONDS, new LinkedBlockingQueue(10));

    /**
     * 到列表页面
     */
    @RequestMapping(value = "/toListPage.do", method = {RequestMethod.GET})
    public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.newWebLogger("加载列表页面，请求参数：" + this.getRequestParameter(request)).setLogOperType(LogOperEnum.REQ)
                .setSysCd(CurrentThreadContext.getCurrentSysCd())
                .setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
                .setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
                .setWarning(false)
                .info();
        ModelAndView view = new ModelAndView("splrate/splRateRelInfo/splRateRelInfoList");

        int len = MagicNumReplaceEnum.REP_NON_YESNO_VAL.getVal();
        List<KeyValueVO> kvList = new ArrayList<>(len);
        KeyValueVO keyValueVO = new KeyValueVO();
        keyValueVO.setKey(BaseConstant.IS_YESNO_NO_STR);
        keyValueVO.setValue("解析失败");
        kvList.add(keyValueVO);
        keyValueVO = new KeyValueVO();
        keyValueVO.setKey(BaseConstant.IS_YESNO_YES_STR);
        keyValueVO.setValue("解析成功");
        kvList.add(keyValueVO);
        /*List<SysDictionaryDTO> dictionaryDTOS = this.sysDictionaryApiService.searchGroup(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), DictionaryConstant.CODE_SYS_YES_NO_CD);
        if (CollectionUtils.isNotEmpty(dictionaryDTOS)) {
            kvList = new ArrayList<>(dictionaryDTOS.size());
            for (SysDictionaryDTO sysDictionaryDTO : dictionaryDTOS) {
                KeyValueVO keyValueVO = new KeyValueVO();
                keyValueVO.setKey(sysDictionaryDTO.getCode());
                keyValueVO.setValue(sysDictionaryDTO.getCodeNm());
                kvList.add(keyValueVO);
            }
        }*/
        view.addObject("isOrSuccess", kvList);
        String parseFileRecId = request.getParameter("parseFileRecId");
        view.addObject("parseFileRecId", parseFileRecId);
        view.addObject("opObjTyp", BasicDataRelOpBizTypCdEnum.SPL_SPLRATE.getTableSimpleNm());
        view.addObject("dataTypCd", BasicDataRelOpBizTypCdEnum.SPL_SPLRATE.getBizTypCd());
        view.addObject("opDataTabNm", BasicDataRelOpBizTypCdEnum.SPL_SPLRATE.getTableNm());
        int isCanAdd = BaseConstant.IS_YESNO_NO;
        if (StringUtils.isNotEmpty(parseFileRecId)) {
            DataResultDTO dataResultDTO = this.parseTempFileRecQueryApiService.selectParseTempFileRecDTOById(Long.valueOf(parseFileRecId), SplSystemConstant.FL_WEB_CHL_CD, SplSystemConstant.FL_SYS_CD, "");
            if (null != dataResultDTO && dataResultDTO.getSuccess() == BaseConstant.IS_YESNO_YES && dataResultDTO.getData() != null) {
                ParseTempFileRecDTO parseTempFileRecDTO = (ParseTempFileRecDTO) dataResultDTO.getData();
                if (FileOpRelStsCdEnum.PARSED_USING.getStsCd().compareTo(parseTempFileRecDTO.getFileStsCd()) == BaseConstant.IS_YESNO_NO) {
                    isCanAdd = BaseConstant.IS_YESNO_YES;
                }
            }
        }
        view.addObject("isCanAdd", isCanAdd);
        return view;
    }

    /**
     * 到新增修改页面
     */
    @RequestMapping(value = "/toAddPage.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView toAddPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.newWebLogger("加载新增.请求参数：" + this.getRequestParameter(request)).setLogOperType(LogOperEnum.REQ)
                .setSysCd(CurrentThreadContext.getCurrentSysCd())
                .setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
                .setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
                .setWarning(false)
                .info();
        ModelAndView view = new ModelAndView("splrate/splRateRelInfo/splRateRelInfoAdd");
        String id = request.getParameter("id");
        view.addObject("id", id);

        List<KeyValueVO> starLvlList = this.sysDictionaryApiService.getKvList(SplRateRelInfoConstant.SPL_RATE_STAR_DIC_CD,
                SplSystemConstant.SPL_SYS_CD,
                SplSystemConstant.DEFAULT_ORG_CD);
        view.addObject("starLvlList", starLvlList);

        List<SplGrpRelInfoSrcEnum> splGrpRelInfoSrcEnums = SplGrpRelInfoSrcEnum.getRelInfoEnumsByGroup("SPLRATE");
        List<KeyValueVO> dataSourceList = null;
        if (CollectionUtils.isNotEmpty(splGrpRelInfoSrcEnums)) {
            dataSourceList = new ArrayList<>(splGrpRelInfoSrcEnums.size());
            for (SplGrpRelInfoSrcEnum srcEnum : splGrpRelInfoSrcEnums) {
                KeyValueVO keyValueVO = new KeyValueVO();
                keyValueVO.setKey(srcEnum.getRelInfoSrc());
                keyValueVO.setValue(srcEnum.getRelInfoSrcDesc());
                dataSourceList.add(keyValueVO);
            }
        }
        view.addObject("dataSourceList", dataSourceList);

        String opTypCd = request.getParameter("opTypCd");
        view.addObject("opTypCd", opTypCd);

        SplRateRelInfoQC splRateRelInfoQC = new SplRateRelInfoQC();
        splRateRelInfoQC.setIsNew(BaseConstant.IS_YESNO_YES);
        splRateRelInfoQC.setIsValid(BaseConstant.IS_YESNO_YES);
        splRateRelInfoQC.setIsDel(BaseConstant.IS_YESNO_NO);
        splRateRelInfoQC.setTabNm("SPL_BSC_INFO");
        splRateRelInfoQC.setIsSuccess(BaseConstant.IS_YESNO_YES);
        DataResultDTO resultDTO = this.splRateRelInfoQueryApiService.searchSplRateRelInfoDTOList(splRateRelInfoQC, null, SplSystemConstant.SPL_SERVICE_CD, CurrentThreadContext.getCurrentUserId() + "查询最新经销商星级评级信息");
        List<SplRateRelInfoDTO> splRateRelInfoDTOList = null;
        String verNum = null;
        Long parseFileRecId = null;
        if (null != resultDTO && resultDTO.getSuccess() == BaseConstant.IS_YESNO_YES) {
            splRateRelInfoDTOList = (List<SplRateRelInfoDTO>) resultDTO.getData();
        }
        if (CollectionUtils.isNotEmpty(splRateRelInfoDTOList)) {
            verNum = splRateRelInfoDTOList.get(BaseConstant.IS_YESNO_NO).getVerNum();
            parseFileRecId = splRateRelInfoDTOList.get(BaseConstant.IS_YESNO_NO).getParseFileRecId();
        } else {
            ParseTempFileRecQC parseTempFileRecQC = new ParseTempFileRecQC();
            parseTempFileRecQC.setIsNew(BaseConstant.IS_YESNO_YES);
            parseTempFileRecQC.setIsValid(BaseConstant.IS_YESNO_YES);
            parseTempFileRecQC.setIsDel(BaseConstant.IS_YESNO_NO);
            parseTempFileRecQC.setBizTypCd(BasicDataRelOpBizTypCdEnum.SPL_SPLRATE.getBizTypCd());
            parseTempFileRecQC.setFileStsCd(FileOpRelStsCdEnum.PARSED_USING.getStsCd());
            DataResultDTO parseTempFileResultDTO = this.parseTempFileRecQueryApiService.searchParseTempFileRecDTOList(parseTempFileRecQC, null, SplSystemConstant.SPL_SERVICE_CD, CurrentThreadContext.getCurrentUserId() + "查询最新经销商星级评级文件信息");
            List<ParseTempFileRecDTO> parseTempFileRecDTOS = null;
            if (null != resultDTO && resultDTO.getSuccess() == BaseConstant.IS_YESNO_YES) {
                parseTempFileRecDTOS = (List<ParseTempFileRecDTO>) resultDTO.getData();
            }
            if (CollectionUtils.isNotEmpty(parseTempFileRecDTOS)) {
                verNum = parseTempFileRecDTOS.get(BaseConstant.IS_YESNO_NO).getVerNum();
                parseFileRecId = parseTempFileRecDTOS.get(BaseConstant.IS_YESNO_NO).getId();
            }
        }
        view.addObject("verNum", verNum);
        view.addObject("parseFileRecId", parseFileRecId);
        String opObjTyp = request.getParameter("opObjTyp");
        String dataTypCd = request.getParameter("dataTypCd");
        String opDataTabNm = request.getParameter("opDataTabNm");
        if (StringUtils.isEmpty(opObjTyp)) {
            opObjTyp = BasicDataRelOpBizTypCdEnum.SPL_SPLRATE.getTableSimpleNm();
        }
        if (StringUtils.isEmpty(dataTypCd)) {
            dataTypCd = BasicDataRelOpBizTypCdEnum.SPL_SPLRATE.getBizTypCd();
        }
        if (StringUtils.isEmpty(opDataTabNm)) {
            opDataTabNm = BasicDataRelOpBizTypCdEnum.SPL_SPLRATE.getTableNm();
        }
        view.addObject("opObjTyp", opObjTyp);
        view.addObject("dataTypCd", dataTypCd);
        view.addObject("opDataTabNm", opDataTabNm);

        BaseLogUtils.newWebLogger("返回数据view:" + JSON.toJSONString(view) + "加载列表页面").setLogOperType(LogOperEnum.REQ)
                .setSysCd(CurrentThreadContext.getCurrentSysCd())
                .setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
                .setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
                .setWarning(false)
                .info();
        return view;
    }

    /**
     * 到修改页面
     */
    @RequestMapping(value = "/toModifyPage.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
        String id = request.getParameter("id");
        ModelAndView view = new ModelAndView("splrate/splRateRelInfo/splRateRelInfoModify");
        view.addObject("id", id);
        return view;
    }

    /**
     * 到详情页面
     */
    @RequestMapping(value = "/toDetailPage.do", method = {RequestMethod.GET})
    public ModelAndView toDetailPage(HttpServletRequest request, HttpServletResponse response) {
        String id = request.getParameter("id");
        ModelAndView view = new ModelAndView("splrate/splRateRelInfo/splRateRelInfoDetail");
        view.addObject("id", id);

        return view;
    }

    /**
     * 初始化列表
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/initList.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object initList(HttpServletRequest request, HttpServletResponse response) {

        String currentPage = request.getParameter("page");
        String pageSize = request.getParameter("pagesize");
        String dataNm = request.getParameter("dataNm");
        String isSuccess = request.getParameter("isSuccess");
        String parseFileRecId = request.getParameter("parseFileRecId");

        Pager page = new Pager();
        if (StringUtils.isNotEmpty(currentPage)) {
            page.setCurrentPage(Integer.parseInt(currentPage));
        }

        if (StringUtils.isNotEmpty(pageSize)) {
            page.setEveryPage(Integer.parseInt(pageSize));
        }

        SplRateRelInfoQC qc = new SplRateRelInfoQC();
        if (StringUtils.isNotEmpty(dataNm)) {
            qc.setDataNm(dataNm);
        }
        if (StringUtils.isNotEmpty(isSuccess)) {
            qc.setIsSuccess(Integer.valueOf(isSuccess));
        } else {
            qc.setIsSuccess(MagicNumReplaceEnum.REP_IGNORE_VAL.getVal());
        }
        if (StringUtils.isNotEmpty(parseFileRecId)) {
            qc.setParseFileRecId(Long.valueOf(parseFileRecId));
        }
        qc.setIsDel(BaseConstant.IS_YESNO_NO);
        qc.setIsValid(MagicNumReplaceEnum.REP_IGNORE_VAL.getVal());
        qc.setIsNew(MagicNumReplaceEnum.REP_IGNORE_VAL.getVal());
        page.setCondition(qc);

        Pager pager = this.splRateRelInfoService.searchListPage(page);
        ListPageVO<SplRateRelInfoVO> listPage = null;
        if (null != pager) {
            List<SplRateRelInfoDTO> splRateRelInfoDTOS = (List<SplRateRelInfoDTO>) pager.getResultList();
            List<SplRateRelInfoVO> list = null;
            if (CollectionUtils.isNotEmpty(splRateRelInfoDTOS)) {
                list = SplRateRelInfoVOTransform.toVOList(splRateRelInfoDTOS);
                SplRateStarLvlEnum starLvlEnum = null;
                for (SplRateRelInfoVO vo : list) {
                    starLvlEnum = SplRateStarLvlEnum.getSplRateStarLvlEnumByBizTypCd(vo.getStarLevel(), null);
                    if (null != starLvlEnum) {
                        vo.setStarLevelNm(starLvlEnum.getStsCdDes());
                    }
                    vo.setDataSourceDesc(SplGrpRelInfoSrcEnum.getRelInfoSrcDescBySrc(vo.getDataSource()));
                }
            }
            listPage = new ListPageVO<SplRateRelInfoVO>(list, pager.getTotalCount());
        } else {
            listPage = new ListPageVO<SplRateRelInfoVO>(new ArrayList<SplRateRelInfoVO>(), BaseConstant.IS_YESNO_NO);
        }
        BaseLogUtils.newWebLogger("加载列表页面.返回数据[" + JSON.toJSONString(listPage) + "]").setLogOperType(LogOperEnum.REQ)
                .setSysCd(CurrentThreadContext.getCurrentSysCd())
                .setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
                .setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
                .setWarning(false)
                .info();
        return listPage;
    }

    /**
     * 新增
     */
    @RequestMapping(value = "/add.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object add(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        BaseLogUtils.newWebLogger("新增对象.请求参数：" + this.getRequestParameter(request)).setLogOperType(LogOperEnum.REQ)
                .setSysCd(CurrentThreadContext.getCurrentSysCd())
                .setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
                .setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
                .setWarning(false)
                .info();
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "新增成功!");
        Long id = null;
        try {
            SplRateRelInfoVO entity = genSplRateRelInfoByRequest(request);
            SplRateRelInfoQC splRateRelInfoQC = new SplRateRelInfoQC();
            splRateRelInfoQC.setIsNew(BaseConstant.IS_YESNO_YES);
            splRateRelInfoQC.setIsValid(BaseConstant.IS_YESNO_YES);
            splRateRelInfoQC.setIsDel(BaseConstant.IS_YESNO_NO);
            splRateRelInfoQC.setIsSuccess(BaseConstant.IS_YESNO_YES);
            splRateRelInfoQC.setTabNm("SPL_BSC_INFO");
            splRateRelInfoQC.setDataId(entity.getDataId());
            splRateRelInfoQC.setDataNm(entity.getDataNm());
            splRateRelInfoQC.setVerNum(entity.getVerNum());
            DataResultDTO resultDTO = this.splRateRelInfoQueryApiService.searchSplRateRelInfoDTOList(splRateRelInfoQC, null, SplSystemConstant.SPL_SERVICE_CD, CurrentThreadContext.getCurrentUserId() + "查询经销商[" + entity.getDataId() + "]星级评级信息");
            List<SplRateRelInfoDTO> splRateRelInfoDTOList = null;
            String verNum = null;
            Long parseFileRecId = null;
            if (null != resultDTO && resultDTO.getSuccess() == BaseConstant.IS_YESNO_YES) {
                splRateRelInfoDTOList = (List<SplRateRelInfoDTO>) resultDTO.getData();
            }
            if (CollectionUtils.isNotEmpty(splRateRelInfoDTOList)) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo("该经销商已经存在星级评级信息,请检查重试!");
                BaseLogUtils.newWebLogger("新增经销商星级评级信息因已存在失败").setLogOperType(LogOperEnum.REQ)
                        .setSysCd(CurrentThreadContext.getCurrentSysCd())
                        .setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
                        .setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
                        .setWarning(false)
                        .warn(LogExceptionEnum.COMMON_CODE_0002);
                return result;
            }
            id = this.splRateRelInfoService.add(entity);
            if (null != id) {
                try {
                    String opObjTyp = request.getParameter("opObjTyp");
                    String dataTypCd = request.getParameter("dataTypCd");
                    String opDataTabNm = request.getParameter("opDataTabNm");
                    String opTypCd = request.getParameter("opTypCd");
                    String opDesc = request.getParameter("opDesc");
                    SplRelDataOpRecDTO splRelDataOpRecDTO = new SplRelDataOpRecDTO();
                    splRelDataOpRecDTO.setPkId(id);
                    splRelDataOpRecDTO.setOpDataTabNm(BasicDataRelOpBizTypCdEnum.SPL_SPLRATE.getTableNm());
                    splRelDataOpRecDTO.setOpAfterData(JSONObject.toJSONString(entity));
                    splRelDataOpRecDTO.setIsValid(BaseConstant.IS_YESNO_YES);
                    splRelDataOpRecDTO.setDataTypCd(StringUtils.isNotEmpty(dataTypCd) ? dataTypCd : BasicDataRelOpBizTypCdEnum.SPL_SPLRATE.getBizTypCd());
                    splRelDataOpRecDTO.setCrtTm(new Date());
                    splRelDataOpRecDTO.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
                    splRelDataOpRecDTO.setCrtUsrNm(CurrentThreadContext.getCurrentUserName());
                    splRelDataOpRecDTO.setOpObjTyp(StringUtils.isNotEmpty(opObjTyp) ? opObjTyp : BasicDataRelOpBizTypCdEnum.SPL_SPLRATE.getTableSimpleNm());
                    splRelDataOpRecDTO.setDataId(entity.getDataId());
                    splRelDataOpRecDTO.setDataNm(entity.getDataNm());
                    splRelDataOpRecDTO.setIsDel(BaseConstant.IS_YESNO_NO);
                    splRelDataOpRecDTO.setOpDesc(opDesc);
                    splRelDataOpRecDTO.setOpTypCd(StringUtils.isNotEmpty(opTypCd) ? opTypCd : CommonOpTypCdEnum.ADD.getOpTypCd());
                    BaseLogUtils.newWebLogger("新增经销商星级评级信息数据日志").setLogOperType(LogOperEnum.REQ)
                            .setSysCd(CurrentThreadContext.getCurrentSysCd())
                            .setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
                            .setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
                            .setWarning(false)
                            .setKeys("splRelDataOpRecDTO", JSONObject.toJSONString(splRelDataOpRecDTO))
                            .info();
                    executorService.execute(new SplRelDataOpRecLogThread(splRelDataOpRecDTO));
                } catch (Exception ex) {
                    BaseLogUtils.newWebLogger("新增经销商星级评级信息数据日志失败,系统错误").setLogOperType(LogOperEnum.REQ)
                            .setSysCd(CurrentThreadContext.getCurrentSysCd())
                            .setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
                            .setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
                            .setWarning(false)
                            .setThrowable(ex)
                            .error(LogExceptionEnum.COMMON_CODE_0099);
                }
            }
            result.setData(id);
            BaseLogUtils.newWebLogger("新增数据").setLogOperType(LogOperEnum.REQ)
                    .setSysCd(CurrentThreadContext.getCurrentSysCd())
                    .setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
                    .setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
                    .setWarning(false)
                    .setKeys("entity", JSONObject.toJSONString(entity))
                    .info();
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            BaseLogUtils.newWebLogger("新增对象失败,业务异常").setLogOperType(LogOperEnum.REQ)
                    .setSysCd(CurrentThreadContext.getCurrentSysCd())
                    .setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
                    .setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
                    .setWarning(false)
                    .setThrowable(ex)
                    .warn(LogExceptionEnum.COMMON_CODE_0002);
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            BaseLogUtils.newWebLogger("新增对象失败,系统异常").setLogOperType(LogOperEnum.REQ)
                    .setSysCd(CurrentThreadContext.getCurrentSysCd())
                    .setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
                    .setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
                    .setWarning(false)
                    .setThrowable(ex)
                    .error(LogExceptionEnum.COMMON_CODE_0099);
        }

        return result;
    }

    /**
     * 修改
     */
    @RequestMapping(value = "/modify.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object modify(HttpServletRequest request, HttpServletResponse response) throws BaseException {

        String id = request.getParameter("id");
        String opObjTyp = request.getParameter("opObjTyp");
        String dataTypCd = request.getParameter("dataTypCd");
        String opDataTabNm = request.getParameter("opDataTabNm");
        String opTypCd = request.getParameter("opTypCd");
        String opDesc = request.getParameter("opDesc");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "修改成功!");
        if (StringUtils.isEmpty(id)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("数据不存在!");
            BaseLogUtils.newWebLogger("修改数据,主键不存在.[id=" + id + "]").setLogOperType(LogOperEnum.REQ)
                    .setSysCd(CurrentThreadContext.getCurrentSysCd())
                    .setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
                    .setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
                    .setWarning(false)
                    .warn(LogExceptionEnum.COMMON_CODE_0002);
            return result;
        }
        try {
            SplRateRelInfoVO entity = genSplRateRelInfoByRequest(request);
            entity.setId(Long.valueOf(id));
            DataResultDTO dataResultDTO = this.splRateRelInfoQueryApiService.selectSplRateRelInfoDTOById(Long.valueOf(id), SplSystemConstant.FL_WEB_CHL_CD, SplSystemConstant.FL_SYS_CD, "");
            if (dataResultDTO == null || dataResultDTO.getSuccess() == BaseConstant.IS_YESNO_NO || null == dataResultDTO.getData()) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo("修改失败!");
                return result;
            }
            SplRateRelInfoDTO oldSplRateRelInfoDTO = (SplRateRelInfoDTO) dataResultDTO.getData();
            String compareDiffInfo = compareDiff(entity, SplRateRelInfoVOTransform.toVO(oldSplRateRelInfoDTO));
            if (StringUtils.isEmpty(compareDiffInfo)) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo("经销商评级数据未做任何修改，请确认再操作!");
                return result;
            }
            SplRelDataOpRecDTO splRelDataOpRecDTO = new SplRelDataOpRecDTO();
            splRelDataOpRecDTO.setPkId(Long.valueOf(id));
            splRelDataOpRecDTO.setOpDataTabNm(StringUtils.isNotEmpty(opDataTabNm) ? opDataTabNm : BasicDataRelOpBizTypCdEnum.SPL_SPLRATE.getTableNm());
            splRelDataOpRecDTO.setOpBeforeData(JSONObject.toJSONString(SplRateRelInfoVOTransform.toVO(oldSplRateRelInfoDTO)));
            splRelDataOpRecDTO.setOpAfterData(JSONObject.toJSONString(entity));
            splRelDataOpRecDTO.setIsValid(BaseConstant.IS_YESNO_YES);
            splRelDataOpRecDTO.setDataTypCd(StringUtils.isNotEmpty(dataTypCd) ? dataTypCd : BasicDataRelOpBizTypCdEnum.SPL_SPLRATE.getBizTypCd());
            splRelDataOpRecDTO.setCompareDiffInfo(compareDiffInfo);
            splRelDataOpRecDTO.setCrtTm(new Date());
            splRelDataOpRecDTO.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
            splRelDataOpRecDTO.setCrtUsrNm(CurrentThreadContext.getCurrentUserName());
            splRelDataOpRecDTO.setOpObjTyp(StringUtils.isNotEmpty(opObjTyp) ? opObjTyp : BasicDataRelOpBizTypCdEnum.SPL_SPLRATE.getTableSimpleNm());
            splRelDataOpRecDTO.setDataId(entity.getDataId());
            splRelDataOpRecDTO.setDataNm(entity.getDataNm());
            splRelDataOpRecDTO.setIsDel(BaseConstant.IS_YESNO_NO);
            splRelDataOpRecDTO.setOpDesc(opDesc);
            splRelDataOpRecDTO.setOpTypCd(StringUtils.isNotEmpty(opTypCd) ? opTypCd : CommonOpTypCdEnum.MDF.getOpTypCd());
            BaseLogUtils.newWebLogger("修改经销商星级评级信息数据日志.[id=" + id + "] DATA:" + JSONObject.toJSONString(splRelDataOpRecDTO))
                    .setLogOperType(LogOperEnum.RESP)
                    .setSysCd(CurrentThreadContext.getCurrentSysCd())
                    .setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
                    .setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
                    .setWarning(false)
                    .info();
            executorService.execute(new SplRelDataOpRecLogThread(splRelDataOpRecDTO));
            boolean success = this.splRateRelInfoService.modify(entity);
            if (!success) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo("修改失败!");
                BaseLogUtils.newWebLogger("修改失败.[id=" + id + "] DATA:" + JSONObject.toJSONString(entity))
                        .setLogOperType(LogOperEnum.RESP)
                        .setSysCd(CurrentThreadContext.getCurrentSysCd())
                        .setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
                        .setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
                        .setWarning(false)
                        .warn(LogExceptionEnum.COMMON_CODE_0002);
            }
            BaseLogUtils.newWebLogger("修改成功.[id=" + id + "] DATA:" + JSONObject.toJSONString(entity))
                    .setLogOperType(LogOperEnum.RESP)
                    .setSysCd(CurrentThreadContext.getCurrentSysCd())
                    .setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
                    .setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
                    .setWarning(false)
                    .info();
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            BaseLogUtils.newWebLogger("修改对象失败,业务异常").setLogOperType(LogOperEnum.REQ)
                    .setSysCd(CurrentThreadContext.getCurrentSysCd())
                    .setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
                    .setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
                    .setWarning(false)
                    .setThrowable(ex)
                    .warn(LogExceptionEnum.COMMON_CODE_0002);
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            BaseLogUtils.newWebLogger("修改对象失败,系统异常").setLogOperType(LogOperEnum.REQ)
                    .setSysCd(CurrentThreadContext.getCurrentSysCd())
                    .setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
                    .setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
                    .setWarning(false)
                    .setThrowable(ex)
                    .error(LogExceptionEnum.COMMON_CODE_0099);
        }

        return result;
    }

    private class SplRelDataOpRecLogThread implements Runnable {

        private SplRelDataOpRecDTO splRelDataOpRecDTO;

        public SplRelDataOpRecLogThread(SplRelDataOpRecDTO dataOpRecDTO) {
            this.splRelDataOpRecDTO = dataOpRecDTO;
        }

        public SplRelDataOpRecDTO getSplRelDataOpRecDTO() {
            return splRelDataOpRecDTO;
        }

        public void setSplRelDataOpRecDTO(SplRelDataOpRecDTO splRelDataOpRecDTO) {
            this.splRelDataOpRecDTO = splRelDataOpRecDTO;
        }

        @Override
        public void run() {
            splRelDataOpRecApiService.addSplRelDataOpRecDTO(this.splRelDataOpRecDTO);
        }
    }

    /**
     * 新旧信息对比
     *
     * @param newVO
     * @param oldVO
     * @return
     */
    private String compareDiff(SplRateRelInfoVO newVO, SplRateRelInfoVO oldVO) {
        StringBuilder stringBuilder = new StringBuilder(8);
        if (newVO.getRateScore().compareTo(oldVO.getRateScore()) != 0) {
            stringBuilder.append("修改前评分为:").append(oldVO.getRateScore()).append(",修改后评分为:").append(newVO.getRateScore()).append(";");
        }
        if (newVO.getStarLevel().compareTo(oldVO.getStarLevel()) != 0) {
            if (stringBuilder.length() > 0) {
                stringBuilder.append("<br>");
            }
            stringBuilder.append("修改前星级为:").append(SplRateStarLvlEnum.getSplRateStarLvlEnumByBizTypCd(oldVO.getStarLevel(),null).getStsCdDes()).append(",修改后星级为:").append(SplRateStarLvlEnum.getSplRateStarLvlEnumByBizTypCd(newVO.getStarLevel(),null).getStsCdDes()).append(";");
        }
        if(StringUtils.isNotEmpty(newVO.getRateLvl()) || StringUtils.isNotEmpty(oldVO.getRateLvl())){
            if (!newVO.getRateLvl().equals(oldVO.getRateLvl())) {
                if (stringBuilder.length() > 0) {
                    stringBuilder.append("<br>");
                }
                stringBuilder.append("修改前评级为:").append(StringUtils.isNotEmpty(oldVO.getRateLvl()) ? oldVO.getRateLvl() : "无").append(",修改后评级为:").append(newVO.getRateLvl());
                stringBuilder.append(";");
            }
        }
        return stringBuilder.toString();
    }

    /**
     * 删除数据
     */
    @RequestMapping(value = "/removeById.do", method = {RequestMethod.POST})
    @ResponseBody
    public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {

        String id = request.getParameter("id");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "删除成功!");
        if (StringUtils.isEmpty(id)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("主键不能为空!");
            return result;
        }
        try {
            this.splRateRelInfoService.removeById(Long.valueOf(id));
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("系统错误,请联系管理员!");
        }

        return result;
    }

    /**
     * 得到一条记录
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getById.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {

        String id = request.getParameter("id");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "操作成功!");
        if (StringUtils.isEmpty(id)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("主键不能为空!");
            BaseLogUtils.newWebLogger("获取数据,主键不存在.[id=" + id + "]").setLogOperType(LogOperEnum.REQ)
                    .setSysCd(CurrentThreadContext.getCurrentSysCd())
                    .setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
                    .setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
                    .setWarning(false)
                    .warn(LogExceptionEnum.COMMON_CODE_0001);
            return result;
        }

        try {
            SplRateRelInfoVO vo = this.splRateRelInfoService.selectById(Long.valueOf(id));
            if (null == vo) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo("数据不存在!");
                BaseLogUtils.newWebLogger("获取数据,数据不存在.[id=" + id + "]").setLogOperType(LogOperEnum.RESP)
                        .setSysCd(CurrentThreadContext.getCurrentSysCd())
                        .setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
                        .setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
                        .setWarning(false)
                        .warn(LogExceptionEnum.COMMON_CODE_0001);
            }
            result.setData(vo);
            BaseLogUtils.newWebLogger("获取数据.[id=" + id + "]").setLogOperType(LogOperEnum.RESP)
                    .setSysCd(CurrentThreadContext.getCurrentSysCd())
                    .setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
                    .setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
                    .setWarning(false)
                    .setKeys("result",JSONObject.toJSONString(result))
                    .info();

        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            BaseLogUtils.newWebLogger("根据主键获取对象失败,业务异常").setLogOperType(LogOperEnum.REQ)
                    .setSysCd(CurrentThreadContext.getCurrentSysCd())
                    .setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
                    .setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
                    .setWarning(false)
                    .setThrowable(ex)
                    .warn(LogExceptionEnum.COMMON_CODE_0001);
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("系统错误,请联系管理员!");
            BaseLogUtils.newWebLogger("根据主键获取对象失败,系统异常").setLogOperType(LogOperEnum.REQ)
                    .setSysCd(CurrentThreadContext.getCurrentSysCd())
                    .setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
                    .setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
                    .setWarning(false)
                    .setThrowable(ex)
                    .error(LogExceptionEnum.COMMON_CODE_0099);
        }

        return result;
    }

    private SplRateRelInfoVO genSplRateRelInfoByRequest(HttpServletRequest request) {
        SplRateRelInfoVO vo = null;
        String id = request.getParameter("id");
        //新增
        if (StringUtils.isEmpty(request.getParameter("dataId"))) {
            throw new BaseException(BaseExceptionConstant.COMMON_0001, "经销商ID为空");
        }
        if (StringUtils.isEmpty(request.getParameter("dataNm"))) {
            throw new BaseException(BaseExceptionConstant.COMMON_0001, "经销商名称为空");
        }
        if (StringUtils.isEmpty(request.getParameter("verNum"))) {
            throw new BaseException(BaseExceptionConstant.COMMON_0001, "经销商星级版本号为空");
        }
        if (StringUtils.isEmpty(request.getParameter("rateScore"))) {
            throw new BaseException(BaseExceptionConstant.COMMON_0001, "经销商评分为空");
        }
        if (StringUtils.isEmpty(request.getParameter("starLevel"))) {
            throw new BaseException(BaseExceptionConstant.COMMON_0001, "经销商星级为空");
        }
        if (StringUtils.isEmpty(request.getParameter("dataSource"))) {
            throw new BaseException(BaseExceptionConstant.COMMON_0001, "经销商星级来源为空");
        }
        String rateScore = request.getParameter("rateScore");
        if (StringUtils.isNotEmpty(rateScore) && ImportSplRateList.checkFildIsNum(rateScore)) {
            String[] splitRateScore = rateScore.split("\\.");
            if (Integer.parseInt(splitRateScore[0]) > 10) {
                throw new BaseException(BaseExceptionConstant.COMMON_0001, "经销商评分超过最大值10！当前值：" + rateScore);
            } else {
                if (splitRateScore.length > 2) {
                    throw new BaseException(BaseExceptionConstant.COMMON_0001, "经销商评分数字错误！当前值：" + rateScore);
                }
            }
        } else {
            throw new BaseException(BaseExceptionConstant.COMMON_0001, "经销商评分为空或非数字，请检查后上传！当前值：" + rateScore);
        }
        DecimalFormat decimalFormat = new DecimalFormat("##.##");
        vo = new SplRateRelInfoVO();
        if (StringUtils.isNotEmpty(id)) {
            //修改
            vo.setId(Long.valueOf(id));
            vo.setMdfTm(new Date());
            vo.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
        } else {
            vo.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
            vo.setCrtTm(new Date());
            vo.setParseFileRecId(Long.valueOf(request.getParameter("parseFileRecId")));
        }
        vo.setRateScore(Double.valueOf(decimalFormat.format(new BigDecimal(rateScore))));
        vo.setDataId(Long.valueOf(request.getParameter("dataId")));
        vo.setDataNm(request.getParameter("dataNm"));
        vo.setDataSource(request.getParameter("dataSource"));
        vo.setStarLevel(Long.valueOf(request.getParameter("starLevel")));
        vo.setRateLvl(request.getParameter("rateLvl"));
        vo.setRateRem(request.getParameter("rateRem"));
        vo.setVerNum(request.getParameter("verNum"));
        vo.setIsNew(BaseConstant.IS_YESNO_YES);
        vo.setTabNm("SPL_BSC_INFO");
        vo.setIsValid(BaseConstant.IS_YESNO_YES);
        vo.setIsSuccess(BaseConstant.IS_YESNO_YES);
        vo.setIsDel(BaseConstant.IS_YESNO_NO);
        return vo;
    }
}

